package weaver.jobs.sinopec.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.cube.cmd.app.SaveModeInfo;
import com.engine.cube.cmd.app.SaveModeRightList;
import com.engine.cube.cmd.form.AddFormCmd;
import com.engine.workflow.biz.FormFieldSetBiz;
import com.engine.workflow.cmd.formManage.fieldManage.SaveFieldCmd;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author dusongsong
 * @date 2024年10月08日 09:31
 */
public class BatchCreateModeTableUtil {

    public static BaseBean baseBean = new BaseBean();

    /**
     * 创建建模主表信息
     *
     * @param user
     * @param mainTableInfo
     * @param formid
     * @return
     */
    public Map<String, Object> createModeMainInfo(User user, JSONObject mainTableInfo, String formid) {
        baseBean.writeLog(">>>>>createModeMainInfo>>>>>" + mainTableInfo + ",formid=" + formid);
        String appid = getAppid();
        JSONArray mainfieldList = new JSONArray();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select t.fieldname,(select labelname from htmllabelinfo where t.fieldlabel=indexid and languageid=7) fieldlabelname," +
                "t.fieldhtmltype,t.type,t.dsporder from workflow_billfield t where t.billid=? and t.detailtable is null ", formid);
        while (rs.next()) {
            JSONObject feildeldjson = new JSONObject();
            feildeldjson.put("fieldname", Util.null2String(rs.getString("fieldname")));
            feildeldjson.put("fieldlabelname", Util.null2String(rs.getString("fieldlabelname")));
            feildeldjson.put("fieldtypeoption", Util.null2String(rs.getString("fieldhtmltype")));
            feildeldjson.put("fieldattr", Util.null2String(rs.getString("type")));
            feildeldjson.put("showorder", Util.null2String(rs.getString("dsporder")));
            mainfieldList.add(feildeldjson);
        }
        JSONObject requestnamejson = new JSONObject();
        requestnamejson.put("fieldname", "requestname");
        requestnamejson.put("fieldlabelname", "请求标题");
        requestnamejson.put("fieldtypeoption", "1");
        requestnamejson.put("fieldattr", "1");
        requestnamejson.put("showorder", "0");
        mainfieldList.add(requestnamejson);
        JSONObject workflowidjson = new JSONObject();
        workflowidjson.put("fieldname", "workflowid");
        workflowidjson.put("fieldlabelname", "流程ID");
        workflowidjson.put("fieldtypeoption", "1");
        workflowidjson.put("fieldattr", "1");
        workflowidjson.put("showorder", "100");
        mainfieldList.add(workflowidjson);
        baseBean.writeLog(">>>>>mainfieldList>>>>>" + mainfieldList);
        return structureModeInfo(appid, mainTableInfo, mainfieldList, user);
    }

    /**
     * 创建建模明细表信息
     * @param user
     * @param detailTableInfo
     * @param newwfformid
     * @param detailtablename
     * @return
     */
    public Map<String, Object> createModeDeatilInfo(User user, JSONObject detailTableInfo, String newwfformid, String detailtablename) {
        baseBean.writeLog(">>>>>createModeDeatilInfo>>>>>" + detailTableInfo + ",newwfformid=" + newwfformid + ",detailtablename=" + detailtablename);
        JSONArray dtlfieldList = new JSONArray();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select t.fieldname,(select labelname from htmllabelinfo where t.fieldlabel=indexid and languageid=7) fieldlabelname," +
                "t.fieldhtmltype,t.type,t.dsporder from workflow_billfield t where t.billid=? and t.detailtable=? ", newwfformid, detailtablename);
        while (rs.next()) {
            JSONObject feildeldjson = new JSONObject();
            feildeldjson.put("fieldname", Util.null2String(rs.getString("fieldname")));
            feildeldjson.put("fieldlabelname", Util.null2String(rs.getString("fieldlabelname")));
            feildeldjson.put("fieldtypeoption", Util.null2String(rs.getString("fieldhtmltype")));
            feildeldjson.put("fieldattr", Util.null2String(rs.getString("type")));
            feildeldjson.put("showorder", Util.null2String(rs.getString("dsporder")));
            dtlfieldList.add(feildeldjson);
        }
        return structureDetailModeInfo(user, detailTableInfo, dtlfieldList);
    }

    /**
     * 创建建模模块信息
     * @param appid
     * @param mainTableInfo
     * @param mainfieldList
     * @param user
     * @return
     */
    private Map<String, Object> structureModeInfo(String appid, JSONObject mainTableInfo, JSONArray mainfieldList, User user) {
        Map<String, Object> resultMap = new HashMap<>();
        baseBean.writeLog(">>>>>structureModeInfo>>>>>mainTableInfo=" + mainTableInfo);
        String modename = Util.null2String(mainTableInfo.getString("modeName"));
        String maintablename = Util.null2String(mainTableInfo.getString("maintablename"));
        Map<String, Object> addForm_params = new HashMap<>();
        String labelname = modename + "记录表";
        addForm_params.put("labelname", labelname);
        addForm_params.put("tablename", maintablename);
        addForm_params.put("modetype", appid);
        addForm_params.put("appid", appid);
        AddFormCmd addFormCmd = new AddFormCmd(addForm_params, user);
        resultMap = addFormCmd.execute(null);
        String newFormid = Util.null2String(resultMap.get("formid"));
        baseBean.writeLog(">>>>>structureModeInfo>>>>>newFormid=" + newFormid);
        JSONArray newfeildArray = new JSONArray();
        for (int i = 0; i < mainfieldList.size(); i++) {
            JSONObject feildeldjson = mainfieldList.getJSONObject(i);
            String fieldname = Util.null2String(feildeldjson.getString("fieldname"));
            String fieldlabelname = Util.null2String(feildeldjson.getString("fieldlabelname"));
            int fieldtypeoption = Util.getIntValue(feildeldjson.getString("fieldtypeoption"));
            int fieldattr = Util.getIntValue(feildeldjson.getString("fieldattr"));
            String showorder = Util.null2String(feildeldjson.getString("showorder"));
            String fieldType = getFiledType(fieldtypeoption, fieldattr);
            Map<String, Object> sfc_params = new HashMap<>();
            sfc_params.put("description", fieldlabelname);
            sfc_params.put("fieldName", fieldname);
            sfc_params.put("ownerTable", maintablename);
            sfc_params.put("orderNo", showorder);
            sfc_params.put("isFromMode", "1");
            sfc_params.put("fieldId", "");
            sfc_params.put("formId", newFormid);
            sfc_params.put("isBill", "1");
            sfc_params.put("tableType", "mainfield");
            //byte[] bytes = Base64.getDecoder().decode(fieldType.replace("\r\n", ""));
            //fieldType = new String(bytes,"UTF-8");
            //base64加密
            byte[] bytes = Base64.getEncoder().encode(fieldType.replace("\r\n", "").getBytes());
            try {
                fieldType = new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sfc_params.put("fieldType", fieldType);
            sfc_params.put("templateField", "false");
            SaveFieldCmd saveFieldCmd = new SaveFieldCmd(sfc_params, user);
            Map<String, Object> fieldMap = saveFieldCmd.execute(null);
            String newFieldid = Util.null2String(fieldMap.get("fieldId"));
            feildeldjson.put("newfieldid", newFieldid);
            newfeildArray.add(feildeldjson);
        }//字段添加结束
        mainTableInfo.put("newFormid", newFormid);
        mainTableInfo.put("newFormName", maintablename);
        resultMap = createModeInfo(appid, mainTableInfo, newfeildArray, user);
        baseBean.writeLog(">>>>>structureModeInfo>>>>>resultMap=" + resultMap);
        return resultMap;
    }

    /**
     * 创建建模明细表模块信息
     * @param user
     * @param detailTableInfo
     * @param fieldList
     * @return
     */
    private Map<String, Object> structureDetailModeInfo(User user, JSONObject detailTableInfo, JSONArray fieldList) {
        Map<String, Object> resultMap = new HashMap<>();
        String newFormid = Util.null2String(detailTableInfo.getString("newFormid"));
        String newDetailtablename = Util.null2String(detailTableInfo.getString("newDetailtablename"));
        int formId = Util.getIntValue(newFormid);
        RecordSet rs = new RecordSet();
        rs.executeQuery("select max(orderid) from Workflow_billdetailtable where billid= ? ", formId);
        int maxOrderId = 0;
        if (rs.next()) {
            maxOrderId = Util.getIntValue(rs.getString(1), 0);
        }
        FormFieldSetBiz formFieldSetBiz = new FormFieldSetBiz(formId, 1, user);
        formFieldSetBiz.setDetailTableOrderId(maxOrderId);
        try {
            formFieldSetBiz.createDetailTable(newDetailtablename);
            formFieldSetBiz.submitOperate();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //往明细表中新增字段和插入数据未完成，主表新增字段改造也未完成。
        for (int i = 0; i < fieldList.size(); i++) {
            JSONObject fieldObject = fieldList.getJSONObject(i);
            int fieldTypeOption = Util.getIntValue(fieldObject.getString("fieldTypeOption"), 0);
            int fieldattr = Util.getIntValue(fieldObject.getString("fieldattr"));
            String fieldType = getFiledType(fieldTypeOption, fieldattr);
            String fieldname = Util.null2String(fieldObject.getString("fieldname"));
            Map<String, Object> sfc_params = new HashMap<>();
            sfc_params.put("description", fieldObject.getString("fieldlabelname"));
            sfc_params.put("fieldName", fieldname);
            sfc_params.put("ownerTable", newDetailtablename);
            sfc_params.put("orderNo", fieldObject.getString("showorder"));
            sfc_params.put("isFromMode", "1");
            sfc_params.put("fieldId", "");
            sfc_params.put("formId", formId);
            sfc_params.put("isBill", "1");
            sfc_params.put("tableType", "detailfield");
            //byte[] bytes = Base64.getDecoder().decode(fieldType.replace("\r\n", ""));
            //fieldType = new String(bytes,"UTF-8");
            //base64加密
            byte[] bytes = Base64.getEncoder().encode(fieldType.replace("\r\n", "").getBytes());
            try {
                fieldType = new String(bytes, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sfc_params.put("fieldType", fieldType);
            sfc_params.put("templateField", "false");
            SaveFieldCmd saveFieldCmd = new SaveFieldCmd(sfc_params, user);
            Map<String, Object> mapresult = saveFieldCmd.execute(null);
            resultMap.put("deatilResultInfo", mapresult);
        }
        return resultMap;
    }

    /**
     * 创建表单信息
     * @param appid
     * @param viewTableInfo
     * @param fieldList
     * @param user
     * @return
     */
    private Map<String, Object> createModeInfo(String appid, JSONObject viewTableInfo, JSONArray fieldList, User user) {
        baseBean.writeLog(">>>>>createModeInfo>>>>>viewTableInfo=" + viewTableInfo);
        String modename = Util.null2String(viewTableInfo.getString("modeName"));
        String newFormid = Util.null2String(viewTableInfo.getString("newFormid"));
        String newFormName = Util.null2String(viewTableInfo.getString("newFormName"));
        int formid = 0;
        String formname = "";
        formid = Util.getIntValue(newFormid);
        formname = Util.null2String(newFormName);
        Map<String, Object> modeinfo_params = new HashMap<>();
        modeinfo_params.put("modename", modename);
        modeinfo_params.put("modetype", appid);
        modeinfo_params.put("formid", formid);
        modeinfo_params.put("modetitle", modename);
        //初始化模块
        SaveModeInfo saveModeInfo = new SaveModeInfo(modeinfo_params, user);
        Map<String, Object> resultMapMode = saveModeInfo.execute(null);
        String modeId = Util.null2String(resultMapMode.get("id"));
        baseBean.writeLog(">>>>>createModeInfo>>>>>resultMapMode=" + resultMapMode);
        //初始化权限
        Map<String, Object> moderight_params = new HashMap<>();
        moderight_params.put("dataLength", "1");
        moderight_params.put("operation", "saveModeRight");
        moderight_params.put("higherlevel_0", "1");
        moderight_params.put("isRoleLimited_0", "0");
        moderight_params.put("importtype_0", "1");
        moderight_params.put("joblevel_0", "2");
        moderight_params.put("layoutorder_0", "-1");
        moderight_params.put("modefieldtype_0", "1");
        moderight_params.put("browsersharetype_0", "1");
        moderight_params.put("relatedid4_0", "2");
        moderight_params.put("righttype_0", "1");
        moderight_params.put("rolefieldtype_0", "1");
        moderight_params.put("rolelevel_0", "0");
        moderight_params.put("sharetype_0", "4");
        moderight_params.put("showlevel_0", "0");
        moderight_params.put("modeid", modeId);
        moderight_params.put("righttype", "3");
        SaveModeRightList saveModeRightList = new SaveModeRightList(moderight_params, user);
        saveModeRightList.execute(null);
        //人员、部门、分部权限
        for (int i = 0; i < fieldList.size(); i++) {
            JSONObject feildeldjson = fieldList.getJSONObject(i);
            String fieldid = Util.null2String(feildeldjson.getString("fieldid"));
            String newfieldid = Util.null2String(feildeldjson.getString("newfieldid"));
            String fieldattr = Util.null2String(feildeldjson.getString("fieldattr"));
            if (newfieldid.length() == 0) {
                newfieldid = fieldid;
            }
            if ("1".equals(fieldattr) || "17".equals(fieldattr)) {//人员
                Map<String, Object> moderight_params_user = new HashMap<>();
                moderight_params_user.put("dataLength", "1");
                moderight_params_user.put("operation", "saveModeRight");
                moderight_params_user.put("higherlevel_0", "1");
                moderight_params_user.put("isRoleLimited_0", "0");
                moderight_params_user.put("importtype_0", "1");
                moderight_params_user.put("joblevel_0", "2");
                moderight_params_user.put("layoutorder_0", "-1");
                moderight_params_user.put("modefieldtype_0", "1");
                moderight_params_user.put("browsersharetype_0", "1");
                moderight_params_user.put("relatedid1000_0", newfieldid);
                moderight_params_user.put("righttype_0", "1");
                moderight_params_user.put("rolefieldtype_0", "1");
                moderight_params_user.put("rolelevel_0", "0");
                moderight_params_user.put("sharetype_0", "1000");
                moderight_params_user.put("showlevel_0", "0");
                moderight_params_user.put("modeid", modeId);
                moderight_params_user.put("righttype", "3");
                SaveModeRightList saveModeRightList_user = new SaveModeRightList(moderight_params_user, user);
                saveModeRightList_user.execute(null);
            } else if ("4".equals(fieldattr) || "57".equals(fieldattr)) {//部门
                Map<String, Object> moderight_params_user = new HashMap<>();
                moderight_params_user.put("dataLength", "1");
                moderight_params_user.put("operation", "saveModeRight");
                moderight_params_user.put("higherlevel_0", "1");
                moderight_params_user.put("isRoleLimited_0", "0");
                moderight_params_user.put("importtype_0", "1");
                moderight_params_user.put("joblevel_0", "2");
                moderight_params_user.put("layoutorder_0", "-1");
                moderight_params_user.put("modefieldtype_0", "2");
                moderight_params_user.put("browsersharetype_0", "1");
                moderight_params_user.put("relatedid1000_0", newfieldid);
                moderight_params_user.put("righttype_0", "1");
                moderight_params_user.put("rolefieldtype_0", "1");
                moderight_params_user.put("rolelevel_0", "0");
                moderight_params_user.put("sharetype_0", "1000");
                moderight_params_user.put("showlevel_0", "0");
                moderight_params_user.put("modeid", modeId);
                moderight_params_user.put("righttype", "3");
                SaveModeRightList saveModeRightList_user = new SaveModeRightList(moderight_params_user, user);
                saveModeRightList_user.execute(null);
            } else if ("164".equals(fieldattr) || "194".equals(fieldattr)) {//分部
                Map<String, Object> moderight_params_user = new HashMap<>();
                moderight_params_user.put("dataLength", "1");
                moderight_params_user.put("operation", "saveModeRight");
                moderight_params_user.put("higherlevel_0", "1");
                moderight_params_user.put("isRoleLimited_0", "0");
                moderight_params_user.put("importtype_0", "1");
                moderight_params_user.put("joblevel_0", "2");
                moderight_params_user.put("layoutorder_0", "-1");
                moderight_params_user.put("modefieldtype_0", "3");
                moderight_params_user.put("browsersharetype_0", "1");
                moderight_params_user.put("relatedid1000_0", newfieldid);
                moderight_params_user.put("righttype_0", "1");
                moderight_params_user.put("rolefieldtype_0", "1");
                moderight_params_user.put("rolelevel_0", "0");
                moderight_params_user.put("sharetype_0", "1000");
                moderight_params_user.put("showlevel_0", "0");
                moderight_params_user.put("modeid", modeId);
                moderight_params_user.put("righttype", "3");
                SaveModeRightList saveModeRightList_user = new SaveModeRightList(moderight_params_user, user);
                saveModeRightList_user.execute(null);

            }
        }

        Map<String, Object> resultModeInfo = new HashMap<>();
        resultModeInfo.put("modeid", modeId);
        resultModeInfo.put("modename", modename);
        resultModeInfo.put("formid", formid);
        resultModeInfo.put("formname", formname);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("resultModeInfo", resultModeInfo);
        return resultMap;
    }

    /**
     * 获取字段类型
     * @param fieldTypeOption
     * @param fieldattr
     * @return
     */
    private String getFiledType(int fieldTypeOption, int fieldattr) {
        String fieldType = "";
        if (fieldTypeOption == 1 && fieldattr == 1) {
            fieldType = "[\"input\",\"text\",\"500\"]";//单行文本
        } else if (fieldTypeOption == 1 && fieldattr == 2) {
            fieldType = "[\"input\",\"int\"]";//整数
        } else if (fieldTypeOption == 2 && fieldattr == 1) {
            fieldType = "[\"textarea\",4]";//多行文本
        } else if (fieldTypeOption == 1 && fieldattr == 3) {
            fieldType = "[\"input\",\"float\",\"2\"]";
        } else if (fieldTypeOption == 3 && fieldattr == 1) {
            fieldType = "[\"browser\",{\"value\":\"1\",\"valueSpan\":\"人力资源\"," +
                    "\"replaceDatas\":[{\"id\":\"1\",\"itemorderid\":\"1\",\"name\":\"人力资源\"," +
                    "\"title\":\"人员-人力资源\",\"parenttitle\":\"人员\"}]}]";//单人力资源
        } else if (fieldTypeOption == 3 && fieldattr == 4) {
            fieldType = "[\"browser\",{\"value\":\"4\",\"valueSpan\":\"部门\"," +
                    "\"replaceDatas\":[{\"id\":\"4\",\"itemorderid\":\"4\",\"name\":\"部门\",\"title\":\"组织-部门\",\"parenttitle\":\"组织\"}]}]";//部门
        } else if (fieldTypeOption == 3 && fieldattr == 164) {
            fieldType = "[\"browser\",{\"value\":\"164\",\"valueSpan\":\"分部\"," +
                    "\"replaceDatas\":[{\"id\":\"164\",\"itemorderid\":\"164\",\"name\":\"分部\",\"title\":\"组织-分部\",\"parenttitle\":\"组织\"}]}]";//分部
        } else if (fieldTypeOption == 3 && fieldattr == 17) {
            fieldType = "[\"browser\",{\"value\":\"17\",\"valueSpan\":\"多人力资源\"," +
                    "\"replaceDatas\":[{\"id\":\"17\",\"itemorderid\":\"17\",\"name\":\"多人力资源\",\"title\":\"人员-多人力资源\"," +
                    "\"parenttitle\":\"人员\"}]}]";
        } else if (fieldTypeOption == 3 && fieldattr == 57) {
            fieldType = "[\"browser\",{\"value\":\"57\",\"valueSpan\":\"多部门\"," +
                    "\"replaceDatas\":[{\"id\":\"57\",\"itemorderid\":\"57\",\"name\":\"多部门\",\"title\":\"组织-多部门\",\"parenttitle\":\"组织\"}]}]";
        } else if (fieldTypeOption == 3 && fieldattr == 194) {
            fieldType = "[\"browser\",{\"value\":\"194\",\"valueSpan\":\"多分部\"," +
                    "\"replaceDatas\":[{\"id\":\"194\",\"itemorderid\":\"194\",\"name\":\"多分部\",\"title\":\"组织-多分部\",\"parenttitle\":\"组织\"}]}]";
        } else if (fieldTypeOption == 6 && fieldattr == 1) {
            fieldType = "[\"upload\",\"file\"]";
        } else {
            fieldType = "[\"input\",\"text\",\"500\"]";//单行文本
        }
        return fieldType;
    }

    /**
     * 获取appid
     * @return
     */
    private String getAppid() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from modeTreeField where treeFieldName = ? and (isdelete=0 or isdelete is null)", "历史数据迁移");
        rs.next();
        return Util.null2String(rs.getString("id"));
    }

    /**
     * 获取明细表列表
     * @param billid
     * @return
     */
    public List<String> getDetailtable(String billid) {
        List<String> detailtableList = new ArrayList<>();
        RecordSet rs = new RecordSet();
        rs.executeQuery("select detailtable from workflow_billfield  where billid=? and detailtable is not null group by detailtable", billid);
        while (rs.next()) {
            String detailtable = Util.null2String(rs.getString("detailtable"));
            detailtableList.add(detailtable);
        }
        return detailtableList;
    }

    /**
     * 创建请求日志表
     * @param user
     * @param detailTableInfo
     * @return
     */
    public Map<String, Object> createRequestLogTable(User user, JSONObject detailTableInfo) {
        String[] fieldName = {"requestname_请求标题,workflowid_工作流id", "nodeid_操作节点id", "lcid_请求id",
                "logtype_签字类型", "operatedate_操作日期", "operatetime_操作时间",
                "operator_操作者", "remark1_意见", "remark_签字信息", "receivedpersons_接收者名称",
                "operatordept_操作者部门", "receivedpersonids_接收人id"};
        JSONArray dtlfieldList = new JSONArray();
        int index = 1;
        for (String field : fieldName) {
            JSONObject feildeldjson = new JSONObject();
            feildeldjson.put("fieldname", field.split("_")[0]);
            feildeldjson.put("fieldlabelname", field.split("_")[1]);
            feildeldjson.put("fieldtypeoption", "1");
            feildeldjson.put("fieldattr", "1");
            feildeldjson.put("showorder", index);
            dtlfieldList.add(feildeldjson);
            index++;
        }
        return structureDetailModeInfo(user, detailTableInfo, dtlfieldList);
    }

}
